const express = require('express');
const cors = require('cors');
const mysql = require('mysql2');

const app = express();
const port = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 数据库连接配置
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'bookshop'
});

// 连接数据库
db.connect(err => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('成功连接到MySQL数据库');
});

// 客户管理API
app.get('/api/customers', (req, res) => {
  const { keyword } = req.query;
  let query = 'SELECT * FROM customers';
  let params = [];

  if (keyword) {
    query = `SELECT * FROM customers WHERE 
             name LIKE ? OR 
             phone LIKE ? OR 
             email LIKE ? OR 
             address LIKE ?`;
    params = Array(4).fill(`%${keyword}%`);
  }

  db.query(query, params, (err, results) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(results);
  });
});

app.post('/api/customers', (req, res) => {
  const { name, phone, email, address } = req.body;
  db.query(
    'INSERT INTO customers (name, phone, email, address) VALUES (?, ?, ?, ?)',
    [name, phone, email, address],
    (err, result) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: result.insertId, ...req.body });
    }
  );
});

app.put('/api/customers/:id', (req, res) => {
  const { name, phone, email, address } = req.body;
  db.query(
    'UPDATE customers SET name=?, phone=?, email=?, address=? WHERE id=?',
    [name, phone, email, address, req.params.id],
    (err) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: req.params.id, ...req.body });
    }
  );
});

app.delete('/api/customers/:id', (req, res) => {
  db.query('DELETE FROM customers WHERE id=?', [req.params.id], (err) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '删除成功' });
  });
});

// 图书管理API
app.get('/api/books', (req, res) => {
  const { keyword } = req.query;
  let query = 'SELECT * FROM books';
  let params = [];

  if (keyword) {
    query = `SELECT * FROM books WHERE 
             title LIKE ? OR 
             author LIKE ? OR 
             publisher LIKE ?`;
    params = Array(3).fill(`%${keyword}%`);
  }

  db.query(query, params, (err, results) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(results);
  });
});

app.post('/api/books', (req, res) => {
  const { title, author, publisher, price, stock } = req.body;
  db.query(
    'INSERT INTO books (title, author, publisher, price, stock) VALUES (?, ?, ?, ?, ?)',
    [title, author, publisher, price, stock],
    (err, result) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: result.insertId, ...req.body });
    }
  );
});

app.put('/api/books/:id', (req, res) => {
  const { title, author, publisher, price, stock } = req.body;
  db.query(
    'UPDATE books SET title=?, author=?, publisher=?, price=?, stock=? WHERE id=?',
    [title, author, publisher, price, stock, req.params.id],
    (err) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: req.params.id, ...req.body });
    }
  );
});

app.delete('/api/books/:id', (req, res) => {
  db.query('DELETE FROM books WHERE id=?', [req.params.id], (err) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '删除成功' });
  });
});

// 文创产品API
app.get('/api/products', (req, res) => {
  const { keyword } = req.query;
  let query = 'SELECT * FROM products';
  let params = [];

  if (keyword) {
    query = `SELECT * FROM products WHERE 
             name LIKE ? OR 
             category LIKE ? OR 
             description LIKE ?`;
    params = Array(3).fill(`%${keyword}%`);
  }

  db.query(query, params, (err, results) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(results);
  });
});

app.post('/api/products', (req, res) => {
  const { name, category, description, price, stock } = req.body;
  db.query(
    'INSERT INTO products (name, category, description, price, stock) VALUES (?, ?, ?, ?, ?)',
    [name, category, description, price, stock],
    (err, result) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: result.insertId, ...req.body });
    }
  );
});

app.put('/api/products/:id', (req, res) => {
  const { name, category, description, price, stock } = req.body;
  db.query(
    'UPDATE products SET name=?, category=?, description=?, price=?, stock=? WHERE id=?',
    [name, category, description, price, stock, req.params.id],
    (err) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ id: req.params.id, ...req.body });
    }
  );
});

app.delete('/api/products/:id', (req, res) => {
  db.query('DELETE FROM products WHERE id=?', [req.params.id], (err) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '删除成功' });
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
}); 